import sys, os
import logging
from flask import Flask, send_from_directory
from flask_appbuilder import SQLA
from flask_appbuilder import AppBuilder
from flask_socketio import SocketIO
from sqlalchemy.engine import Engine
from sqlalchemy import event
from .security import MySecurityManager
from app.Index import MyIndexView

logging.basicConfig(format='%(asctime)s:%(levelname)s:%(name)s:%(message)s')
logging.getLogger().setLevel(logging.DEBUG)

base_folder = None
template_folder='templates'
if getattr(sys, 'frozen', False):
    base_folder = os.path.dirname(sys.executable)
    template_folder = os.path.join(base_folder, 'templates')
app = Flask(__name__, template_folder=template_folder, root_path=base_folder)
app.config.from_object('config')
db = SQLA(app)
appbuilder = AppBuilder(app, db.session, security_manager_class=MySecurityManager, indexview=MyIndexView)
if getattr(sys, 'frozen', False):
    fab_static_folder = app.blueprints['appbuilder'].static_folder
    fab_root_folder = app.blueprints['appbuilder'].root_path
    app.blueprints['appbuilder'].static_folder = fab_static_folder.replace(fab_root_folder, base_folder)
    app.blueprints['appbuilder'].root_path = base_folder

socketio = SocketIO(app, async_mode='eventlet', engineio_logger=False)

# disable info logs for such modules
for name in ['engineio', 'socketio', 'asyncio']:
    logger = logging.getLogger('engineio')
    logger.setLevel(logging.WARN)


@event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
    cursor = dbapi_connection.cursor()
    cursor.execute("PRAGMA foreign_keys=ON")
    cursor.close()
    

from app import models
# from app.views import views
from app.views import BackEnd
from app.views import Log
# from app.views import CheckUnit
# from app.views import Selector
# from app.views import Condition
# from app.views import Vendor
from app.views import Running

# from app import BackgroundTask